package com.ys.controller.api.finance;

import com.ys.config.MenuId;
import com.ys.entity.finance.TcwExpenseSettleReturn;
import com.ys.entity.sys.YsCol;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.service.finance.TcwExpenseSettleReturnService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 费用结算返还单
 */
@Controller
@RequestMapping("/api/inter/tcwExpenseSettleReturn")
public class ApiInterTcwExpenseSettleReturnController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwExpenseSettleReturnController.class);

    @Autowired
    private CommonApiService<TcwExpenseSettleReturn> commonApiService;

    @Autowired
    private TcwExpenseSettleReturnService tcwExpenseSettleReturnService;

    @Autowired
    private YspTaskService yspTaskService;

    //菜单id
    private Long menuId = MenuId.TCW_ExpenseSettleReturn;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwExpenseSettleReturn setSeachSql(TcwExpenseSettleReturn cond){

        cond.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addField("U.UserId AS userld")

        .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间
                //.addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间

        .addLeftJoin("TCW_ExpenseSettleReturnItem S ON S.Pbid = A.Bid")//子表
                .addField("S.ReturnAmount AS returnAmount")//返还金额
                .addField("S.ReturnReason AS returnReason")//返还原因（备注）
                .addField("S.AccountDetailedRemark AS vbz")//备注


                .addLeftJoin("TCW_AccountDetailedForCompany D ON D.Id = S.AccountDetailedForCompanyId")//流水表
                //.addField("D.Guid AS guid")//流水唯一识别码
                .addField("D.Vjylx AS vjylx")//交易类型
                .addField("D.Vgsbm AS vgsbm")//运营公司编码
                .addField("D.Vgsjc AS vgsjc")//运营公司简称
                .addField("D.Vgsbmp AS vgsbmp")//对方公司编码
                .addField("D.Vgsjcp AS vgsjcp")//对方公司简称
                .addField("D.Fje AS fje")//交易金额
                //.addField("D.Vbz AS vbz")//备注
                .addField("D.Djysj AS djysj")//交易发生时间
                .addField("D.Dshsj AS dshsj")//交易审核时间
                .addField("D.WriteTime AS writeTime")//记账时间

                .addLeftJoin("TS_UserInfo CU ON CU.UserId = U.UserId")//用户信息表
                .addLeftJoin("TS_OrganizationInfo UO ON UO.Id = CU.OrgId")//用户所属机构
                .addField("UO.OrgId AS orgId")

        //排序
        .setOrderby("A.Bid DESC");

        cond = commonApiService.dataAuth(menuId, cond);
        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tcwExpenseSettleReturn:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwExpenseSettleReturn cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwExpenseSettleReturn cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcwExpenseSettleReturn> util = new ExportExcelUtils<>(new TcwExpenseSettleReturn());
            String toFilePath = util.exportExcel(listData, listField, "费用结算返还单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequiresPermissions("tcwExpenseSettleReturn:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcwExpenseSettleReturnService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("tcwExpenseSettleReturn:add")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcwExpenseSettleReturnService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions("tcwExpenseSettleReturn:add")
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcwExpenseSettleReturnService.del(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 删除列表
     */
    @RequiresPermissions("tcwExpenseSettleReturn:add")
    @RequestMapping("/toDelByItem")
    @ResponseBody
    public R toDelByItem(HttpServletRequest request,@RequestParam("list") List<String> idList){
        try {
            //删除
            for (int i = 0; i < idList.size(); i++) {
                tcwExpenseSettleReturnService.toDelByItem(Long.parseLong(idList.get(i)));
            }
            return R.ok();
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 流转通过
     */
    @RequiresPermissions("tcwExpenseSettleReturn:add")
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwExpenseSettleReturnService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions("tcwExpenseSettleReturn:add")
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request,  Long id, String reason){
        try {
            TcwExpenseSettleReturn tcwExpenseSettleReturn = new TcwExpenseSettleReturn().setId(id).queryFirst();
            return yspTaskService.flowRefuse(tcwExpenseSettleReturn.getBid(), reason, ShiroUtils.getUserId());

        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转驳回
     */
    @RequiresPermissions("tcwExpenseSettleReturn:add")
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TcwExpenseSettleReturn tcwExpenseSettleReturn = new TcwExpenseSettleReturn().setId(id).queryFirst();
            return yspTaskService.flowInit(tcwExpenseSettleReturn.getBid(), reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 弹出框（线上组装报错调用）
     */
    @RequestMapping("/searchForModalByOnlineError")
    @ResponseBody
    public LayuiTableVoJA searchForModalByOnlineError(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcwExpenseSettleReturn cond,String conditions
    ){
        try {
            logger.info("conditions："+conditions);
            cond
                    .addLeftJoin("TCW_ExpenseSettleReturnItem S ON S.Pbid = A.Bid")//子表
                    .addField("S.ReturnAmount AS _ys_returnAmount")//返还金额
                    .addField("S.AccountDetailedRemark AS _ys_accountDetailedRemark")//备注
                    .addField("S.Id AS expenseSettleReturnItemId")//子表id

                    .addLeftJoin("TCW_AccountDetailedForCompany D ON D.Id = S.AccountDetailedForCompanyId")//流水表
                    .addField("D.Vjylx AS vjylx")//交易类型
                    .addField("D.Vgsbm AS vgsbm")//运营公司编码
                    .addField("D.Vgsjc AS vgsjc")//运营公司简称
                    .addField("D.Vgsbmp AS vgsbmp")//对方公司编码
                    .addField("D.Vgsjcp AS vgsjcp")//对方公司简称
                    .addField("D.Fje AS fje")//交易金额
                    //.addField("D.Vbz AS vbz")//备注
                    .addField("D.Djysj AS djysj")//交易发生时间
                    .addField("D.Dshsj AS dshsj")//交易审核时间
                    .addField("D.WriteTime AS writeTime")//记账时间



                    //排序
                    .setOrderby("A.Bid DESC");

            //权限
            cond = commonApiService.dataAuth(menuId, cond);

            //***锁查询条件
            {
                //锁：费用结算返还单返还的总金额≤该采购订单子件缺失金额
                String returnAmount = ConditionUtil.getConditionValue(conditions, "_ys_returnAmount");//返还金额
                if (returnAmount != null) {
                    cond.where("S.ReturnAmount <=" + returnAmount);
                }
                //锁：采购订单号 purchaseOrderBid、商品编码 spbm
                String remark = ConditionUtil.getConditionValue(conditions, "_ys_accountDetailedRemark");//备注
                if (remark != null) {
                    //String[] remarkByArr = remark.split("");
                    cond.where("S.AccountDetailedRemark LIKE '" + remark + "'");
                }

                //锁：交易类型
                cond.where("D.Vjylx = '" + TransactionTypeEnum.BusinessType.CGFW_CGCB.name + "'");

                //已被调用过的不调用
                cond.where("(SELECT count(1) FROM TCW_ExpenseSettleReturnUsed UU WHERE UU.ExpenseSettleReturnItemId = A.Id) = 0 ");

                //已生效
                cond.setEffectStock(1);

            }


            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }







}